package com.ieducc.ffmpegdemo.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.ieducc.ffmpegdemo.ffmpegutil.FfmpegService;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class OssClient {

    static String endPoint = "oss-cn-hangzhou.aliyuncs.com";

    static String keyId = "LTAI4GHfCsHRB3AM4eatPxCp";

    static String keySecret = "mII3D46Ip2HKWPPV4yyKbQoHyl88QW";

    static String bucketName = "studycloud-test";

    static OSS ossClient = null;

    static String[] suffixArrays = {"jpg", "jpeg", "png", "bmp", "gif", "mp3", "wma", "avi", "rm", "rmvb", "flv", "mpg", "mov", "mkv", "mpeg", "mp4", "wmv", "asf", "vob", "ts",
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"};

    static List suffixList = null;

    static int maxKeys = 1000;
    static int totalCount = 0;
    static String prefix = "https://test.ieducc.com/";
    static String mp4Suffix = "mp4";


    /**
     * @desc 初始化oss
     */

    public static void initOSSServer() {
        if (suffixList == null || suffixList.size() == 0) {
            suffixList = Arrays.asList(suffixArrays);
        }

        ossClient = null;
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(600000);
        conf.setMaxErrorRetry(3);
        ossClient = new OSSClientBuilder().build(endPoint, keyId, keySecret);

    }

    /**
     * @desc 计算全部文件数
     */

    public static void getAllCount() {
        initOSSServer();
        try {
            String nextMarker = null;
            ObjectListing objectListing;
            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                totalCount = totalCount + sums.size();
                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } catch (OSSException oe) {
            System.out.println("OSSException--------------");
        } catch (ClientException ce) {
            System.out.println("ClientException--------------");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        System.out.println("totalCount---------->>>" + totalCount);
    }

    /**
     * @desc 计算
     */
    public static void getAllVideoSize() {
        initOSSServer();
        String allUrl = "";

//        maxKeys = 10;// 临时赋值测试使用
//        try {
//            String nextMarker = null;
//            ObjectListing objectListing;
//            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
//            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
//
//            for (OSSObjectSummary s : sums) {
//
//                allUrl = prefix + s.getKey();
//                String suffix = allUrl.substring(allUrl.lastIndexOf(".") + 1);
//
//                if (suffix.equalsIgnoreCase(mp4Suffix)) {
//                    long size = s.getSize();// 视频大小
//                    double totalSize = new BigDecimal(size).divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP).doubleValue();
//                    System.out.println("视频地址：" + allUrl + "   |   视频大小：" + totalSize);
//                }
//            }
//
//        } catch (Exception ce) {
//            System.out.println("ClientException--------------");
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }


        // 总大小 Map
        Map<String, Double> totalSizeMap = new HashMap<>();
        // 总数 Map
        Map<String, Integer> totalCountMap = new HashMap<>();
        try {
            String nextMarker = null;
            ObjectListing objectListing;
            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                totalCount = totalCount + sums.size();
                for (OSSObjectSummary s : sums) {
                    allUrl = prefix + s.getKey();
                    String suffix = allUrl.substring(allUrl.lastIndexOf(".") + 1);
                    if (suffix.length() >= 5) {
                        continue;
                    }
                    log.info(allUrl);
                    long size = s.getSize();// 视频大小
                    double currentSize = new BigDecimal(size).divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP).doubleValue();

                    if (totalSizeMap.containsKey(suffix)) {
                        Double oldSize = totalSizeMap.get(suffix);
                        oldSize = oldSize + currentSize;
                        totalSizeMap.put(suffix, oldSize);

                        Integer count = totalCountMap.get(suffix);
                        count = count + 1;
                        totalCountMap.put(suffix, count);
                    } else {
                        totalSizeMap.put(suffix, currentSize);
                        totalCountMap.put(suffix, 1);
                    }

                }
                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } catch (Exception ce) {
            System.out.println("Exception--------------");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        for (String suffer : totalSizeMap.keySet()) {
            if (totalCountMap.get(suffer) < 10) {
                continue;
            }
            if (totalSizeMap.get(suffer) < 20) {
                continue;
            }
            System.out.println("" + suffer + "," + totalCountMap.get(suffer) + "," + totalSizeMap.get(suffer));
        }

    }


    /**
     * @desc 查询比特率大于1024的视频总量
     */
    public static void getVideoGt1024() {
        initOSSServer();
        String allUrl = "";
//        maxKeys = 10;// 临时赋值测试使用
//        Map<String, Double> videoMap = new HashMap();
//        try {
//            ObjectListing objectListing;
//            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMaxKeys(maxKeys));
//            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
//            for (OSSObjectSummary s : sums) {
//                allUrl = prefix + s.getKey();
//                String suffix = allUrl.substring(allUrl.lastIndexOf(".") + 1);
//                System.out.println("allUrl------------->>>" + allUrl);
//                if (suffix.equalsIgnoreCase(mp4Suffix)) {
//                    final int bitRate = new FfmpegService().getInfoByUrl(allUrl).getVideo().getBitRate();
//                    System.out.println("bitRate------->>>" + bitRate);
//                    if (bitRate <= 1024) {
//                        continue;
//                    }
//                    long size = s.getSize();// 视频大小
//                    double videoSize = new BigDecimal(size).divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP).doubleValue();
////                    System.out.println("视频地址：" + allUrl + "   |   视频大小：" + totalSize);
//                    videoMap.put(allUrl, videoSize);
//                }
//            }
//        } catch (Exception ce) {
//            System.out.println("ClientException--------------");
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }
        Map<String, Double> videoMap = new HashMap();
        try {
            String nextMarker = null;
            ObjectListing objectListing;
            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                totalCount = totalCount + sums.size();
                for (OSSObjectSummary s : sums) {
                    allUrl = prefix + s.getKey();
                    String suffix = allUrl.substring(allUrl.lastIndexOf(".") + 1);

                    if (suffix.equalsIgnoreCase(mp4Suffix)) {
                        final int bitRate = new FfmpegService().getInfoByUrl(allUrl).getVideo().getBitRate();
                        System.out.println("allUrl:" + allUrl);

                        if (bitRate <= 1024) {
                            continue;
                        }

                        long size = s.getSize();// 视频大小
                        double videoSize = new BigDecimal(size).divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP).doubleValue();
                        videoMap.put(allUrl, videoSize);
                    }
                }
                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } catch (Exception ce) {
            System.out.println("Exception--------------");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        for (String url : videoMap.keySet()) {
            System.out.println("" + url + "," + videoMap.get(url));
        }
    }

    /**
     * @desc 获取大于100M的ppt
     */
    public static void getPPTGt100M() {
        initOSSServer();
        String allUrl = "";
        Map<String, Double> pptMap = new HashMap();
        try {
            String nextMarker = null;
            ObjectListing objectListing;
            do {
                objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(maxKeys));
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                totalCount = totalCount + sums.size();
                for (OSSObjectSummary s : sums) {
                    allUrl = prefix + s.getKey();
                    String suffix = allUrl.substring(allUrl.lastIndexOf(".") + 1);

                    if (suffix.equalsIgnoreCase("ppt") || suffix.equalsIgnoreCase("pptx")) {
                        System.out.println("allUrl:" + allUrl);

                        long size = s.getSize();// 视频大小
                        double pptSize = new BigDecimal(size).divide(new BigDecimal(1048576), 2, RoundingMode.HALF_UP).doubleValue();
                        if (pptSize > 100) {
                            pptMap.put(allUrl, pptSize);
                        }
                    }
                }
                nextMarker = objectListing.getNextMarker();

            } while (objectListing.isTruncated());
        } catch (Exception ce) {
            System.out.println("Exception--------------");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        for (String url : pptMap.keySet()) {
            System.out.println("" + url + "," + pptMap.get(url));
        }
    }


    public static void main(String[] args) {
        //getAllCount();
        //getAllVideoSize();
        //getVideoGt1024();
        getPPTGt100M();

    }
}
